<?php
namespace app\listener\admin;

use app\common\model\order\ShopOrderModel;
use app\common\service\order\ShopOrderService;
use app\common\service\webscoket\CacheRedisService;
use app\job\OrderScheduleJob;
use think\facade\Log;
use think\facade\Queue;
use Swoole\Timer;

class OrderScheduleListener
{

    /**
     * 订单上架
     * @Author: 易军辉
     * @DateTime:2024-08-22 15:01
     * @param $event
     */
    public function handle($event): void
    {
        /********************当服务启动时判断队列是否有任务，没有清空一次缓存*****************************/
        if(Queue::size()<=0){
            $del_res = CacheRedisService::del('OrderScheduleListener');
        }
        Timer::tick(1000*30, function (){
            Log::write("订单上架：".date('Y-m-d H:i:s'));
            try {
                $where =[
                    ['is_delete','=',0],
                    ['status','=',ShopOrderModel::getStatus('o_listing',1)],
                    ['estimate_advertising_time','<=',date('Y-m-d H:i:s')]
                ];
                $ids = CacheRedisService::sMembers('OrderScheduleListener');
                if($ids){
                    $where[] = ['id','not in',$ids];
                }
                $list = ShopOrderService::getList($where,0,0,['estimate_advertising_time'=>'asc'],'id,status,old_status,is_self_selection,merchant_id');
                if($list){
                    Log::write("订单上架数量：".count($list));
                    CacheRedisService::sAdd('OrderScheduleListener',array_column($list,'id'));
                    Queue::push(OrderScheduleJob::class, $list);
                }
            } catch (\Exception $e) {
                Log::error("订单上架报错：".$e->getMessage());
            }
        });
    }
}
